package com.lzwork.gpt.utility.controller;

import java.io.File;
import java.util.Map;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.lzwork.gpt.utility.job.FileParseJob;
import com.lzwork.utility.file.FileUtility;
import com.lzwork.utility.str.StrUtility;
import com.lzwork.web.BaseController;

/**
 * @author LiZheng
 * @date 2024年3月13日 15:32:25
 */

public abstract class GptJobController extends BaseController
{
	protected abstract FileParseJob getParser(String key, Map<?, ?> param);

	protected abstract File rootFolder();

	@PostMapping(value = "fileParse", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public JSONObject fileParse(@RequestBody Map<?, ?> map)
	{
		String type = getMapStr(map, "type");
		if (!StrUtility.stringValid(type))
			return errReturn("Missing paramter: " + type);

		Map<?, ?> param = getSubMap(map, "param", false);

		FileParseJob job = getParser(type, param);
		if (job == null)
			return errReturn("No parser job type: " + type);

		String inputName = getMapStr(map, "input", job.getSetting().defInput());
		String outputName = getMapStr(map, "output", job.getSetting().defOutput());
		String legacyName = getMapStr(map, "legacy");

		File input = FileUtility.getFileSafe(rootFolder(), inputName);
		if (!input.exists() || !input.isFile())
			return errReturn("No input file found: " + input.getName());

		File output = FileUtility.getFileSafe(rootFolder(), outputName);
		File legacy = FileUtility.getFileSafe(rootFolder(), legacyName);

		if (!legacy.exists() || !legacy.isFile())
			legacy = null;

		JSONObject parsed = job.doParse(input, output, legacy);

		JSONObject result = new JSONObject();
		result.put("result", parsed);

		return result;
	}
}
